/*
 * discountDAO.java
 *
 * Created on March 31, 2007, 1:00 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.mystuff.printconversion;

import java.util.*;
import java.sql.*;

/**
 *
 * @author Sam Griffiths
 */
public class discountDAO {
    
    //initialize variables
    private static discountDAO instance;
    private String discountid;
    private static Cache cache;
    
    /** Creates a new instance of paymentDAO */
    public discountDAO() {
    cache = Cache.getInstance();
    }
        
    //returns an instance of discountDAO
    public static synchronized discountDAO getInstance() {
        if (instance == null) {
            instance = new discountDAO();
            
        }
        return instance;
    }
    
    //creates a new discountBO with id initialized
    public discountBO create(){
        discountid = Guid.generate();
        discountBO dis = new discountBO(discountid);
        cache.put(discountid, dis);
        return dis;
    }
    
    /*
     *This method reads all stores from the database and returns
     *them in an ArrayList
     */
    public synchronized ArrayList<discountBO> readALL() throws DataException {
        ArrayList<discountBO> dislist = new ArrayList();
        Connection conn = null;
        try {
            //getConnection, create an sql statement, execute the Query
            conn = ConnectionPool.getInstance().get();
            //System.out.println("Check");
            Statement st = conn.createStatement();
            //System.out.println("Executing Query");
            ResultSet rs = st.executeQuery("SELECT * FROM DISCOUNT_TABLE");
            //System.out.println("Execute Succesful");
            
            while(rs.next()){
                //creates discountBO's from resultset and adds them to dislist (the arraylist)'
                discountBO dis = new discountBO(rs.getString("DSID"));
                dis.setPercent(Double.valueOf(rs.getString("PERCENT").trim()).doubleValue());//artist
                dis.setQuantity(Double.valueOf(rs.getString("QUANTITY").trim()).doubleValue());//album
                dis.setAlreadyInDatabase(true);
                dislist.add(dis);
            }
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
            }
            
            throw new DataException("Could not retrieve records", e);
        }
        
        return dislist;
    }
    
    //Creates a connection, calls another read method, hands in connection, and discountid
    //returns store object
    public synchronized discountBO read(String discountid) throws DataException{
        discountBO dis = null;
        Connection conn = null;
        try {
            conn = ConnectionPool.getInstance().get();
            if(cache.containsKey(discountid))
                dis = (discountBO)cache.get(discountid);
            else
                dis = read(conn, discountid);
            
            ///////////////////////////////////////////
            // call read with a connection (the other read method in this class)
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
            }
            
            throw new DataException("Could not retrieve records", e);
        }
        
        return dis;
    }
    
    //exactly like ReadAll, but only reads in one object
    public synchronized discountBO read(Connection conn, String id){
       discountBO dis = null;
        try{
        Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM STORE_TABLE WHERE STORE_ID='"+id+"'");
            dis = new discountBO(id);
            while(rs.next()){
                dis.setPercent(Double.valueOf(rs.getString("PERCENT").trim()).doubleValue());//artist
                dis.setQuantity(Double.valueOf(rs.getString("QUANTITY").trim()).doubleValue());//album
                dis.setAlreadyInDatabase(true);         
            }
       }catch(Exception e){}
       cache.put(id, dis);
       return dis;
    }
    
    /////////////save////////////////////
    //calls another save after checking the dirty first to make sure someones not tryingt to resave something and
    //waste precious processing time
    public synchronized boolean save(discountBO dis) throws DataException {
       System.out.println("Save entrance accessed");
        Connection conn = null;
        try {
            
            conn = ConnectionPool.getInstance().get();
            if(dis.isDirty())
                save(conn,dis);
            dis.setDirty(false);
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
            }
            
            throw new DataException("Could not retrieve records", e);
        }
        
        return true;
        }
    
    //checks object to see if it is already is in the database
    //if object is already in database, run an update
    //if object is not in database, run an insert
    public synchronized void save(Connection conn, discountBO dis){
        System.out.println("Second Save Accessed");
        try{
            Statement st = conn.createStatement();
           
            //System.out.println("First Query Skipped");
            if(false == dis.isAlreadyInDatabase()){
                
                String queryString = "INSERT INTO DISCOUNT_TABLE VALUES (?,?,?)";
                PreparedStatement pstmt = conn.prepareStatement(queryString);
               
                //String aString = Double.toString(aDouble);
                pstmt.setString(1,dis.getDiscountId());
                pstmt.setString(2,Double.toString(dis.getQuantity()));
                pstmt.setString(3,Double.toString(dis.getPercent()));
                pstmt.execute();
                pstmt.close();
                dis.setAlreadyInDatabase(true);
            } else{
            
                String queryString = "UPDATE DISCOUNT_TABLE SET QUANTITY = ?, PERCENT = ? WHERE DISID = ? ";
                PreparedStatement pstmt = conn.prepareStatement(queryString);
                pstmt.setString(1,Double.toString(dis.getQuantity()));//name
                pstmt.setString(2,Double.toString(dis.getPercent()));
                pstmt.setString(3,dis.getDiscountId());
                pstmt.execute();
                pstmt.close();
                
            }
        }catch(Exception e){}
    }
    
    /////////////delete////////////////////////
    // ya we're not going to delete stores, if we go out of business, we won't need a delete anyways'
    
}
